<?php

namespace App\Http\Controllers\Admin\Wechat;
use App\Models\Reply;
use Log;
use EasyWeChat\Message\Text;
use EasyWeChat\Message\News;
class WechatController extends Controller
{

    /**
     * 处理微信的请求消息
     *
     * @return string
     */
    public function serve()
    {
        Log::info('request arrived.'); //# 注意：Log 为 Laravel 组件，所以它记的日志去 Laravel 日志看，而不是 EasyWeChat 日志

        $wechat = app('wechat');
        $wechat->server->setMessageHandler(function($message){
            //return "欢迎关注 开发平台！";
            switch ($message->MsgType) {
                case 'event':
                    // 事件消息...
                    break;
                case 'text':

                    return $this->text($message);
                    break;
                case 'image':
                    // 图片消息...
                    break;
                case 'voice':
                    // 语音消息...
                    break;
                case 'video':
                    // 视频消息...
                    break;
                case 'location':
                    // 坐标消息...
                    break;
                case 'link':
                    // 链接消息...
                    break;
                // ... 其它消息
                default:
                    // code...
                    break;
            }
        });

        Log::info('return response.');

        return $wechat->server->serve();
    }

    protected function text($message){
        //return "欢迎关注 开发平台！";
        if($message->Content){
            $reply = Reply::where('keyword','=',$message->Content)->first();
            if($reply){
                if($reply->msgtype=='text'){
                    $message = new Text(['content' => $reply->content]);
                }elseif($reply->msgtype=='news'){
                    $message = new News([
                        'title'       => $reply->title,
                        'description' => $reply->description,
                        'url'         => $reply->url,
                        'image'       => asset($reply->picurl),
                        // ...
                    ]);
                }
                
            }else{
                $message = new Text(['content' => 'Ohkj!']);
            }
        }
        return $message;
    }
}